package com.jwsoft.manager.core.integration.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.core.helper.DictHelper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.enums.AreaEnum;
import com.jwsoft.manager.common.enums.EduAreaCodeEnum;
import com.jwsoft.manager.common.vo.eduClassAdviser.EduClassAdviserVO;
import com.jwsoft.manager.common.vo.eduClassStudent.EduClassStudentVO;
import com.jwsoft.manager.common.vo.eduClassStudentKey.EduClassStudentKeyInfoVO;
import com.jwsoft.manager.common.vo.eduSchool.EduSchoolVO;
import com.jwsoft.manager.core.dao.model.EduClassAdviser;
import com.jwsoft.manager.core.dao.model.EduClassStudent;
import com.jwsoft.manager.core.dao.model.EduSchool;
import com.jwsoft.manager.core.dao.service.EduClassAdviserService;
import com.jwsoft.manager.core.dao.service.EduClassStudentService;
import com.jwsoft.manager.core.dao.service.EduSchoolService;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import cn.hutool.core.convert.Convert;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.bifang.engine.assistant.core.exception.AppException;
import org.springframework.util.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.jwsoft.manager.common.vo.eduClassStudentKey.EduClassStudentKeyVO;
import com.jwsoft.manager.common.vo.eduClassStudentKey.EduClassStudentKeyKeyVO;
import com.jwsoft.manager.common.vo.eduClassStudentKey.EduClassStudentKeyQueryVO;
import com.jwsoft.manager.core.integration.EduClassStudentKeyIntegration;
import com.jwsoft.manager.core.dao.service.EduClassStudentKeyService;
import com.jwsoft.manager.core.dao.model.EduClassStudentKey;

/**
 * 分班学生重点名单管理业务实现类
 *
 * @author chenzh
 * @since 2023-08-21
 */
@ApiService(funcCode = "eduClassStudentKey", title = "分班学生重点名单管理")
public class EduClassStudentKeyIntegrationImpl implements EduClassStudentKeyIntegration {

    @Autowired
    public EduClassStudentKeyService eduClassStudentKeyService;

    @Autowired
    private DictHelper dictHelper;

    @Autowired
    private EduSchoolService eduSchoolService;

    @Autowired
    private EduHelper eduHelper;

    @Autowired
    private EduClassStudentService eduClassStudentService;

    @Autowired
    private EduClassAdviserService eduClassAdviserService;

    @Override
    @OpApi(funcCode = "eduClassStudentKey0001", title = "分班学生重点名单管理分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduClassStudentKeyInfoVO> getList(EduClassStudentKeyQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        if (ObjectUtils.isEmpty(vo.getAreaCode())) {
            vo.setAreaCode(SessionUtil.getAreaCode());
        }
        if (ObjectUtils.isEmpty(vo.getYear())) {
            vo.setYear(eduHelper.thisYear());
        }
        if (StringUtils.isNotBlank(vo.getSchoolId())) {
            EduSchoolVO eduSchoolVO = eduSchoolService.getDetail(vo.getSchoolId());
            if (eduSchoolVO != null) {
                vo.setAreaCode(eduSchoolVO.getAreaCode());
            } else {
                vo.setSchoolId(null);
            }
        }
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        QueryWrapper<EduClassStudentKey> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(EduClassStudentKey::getYear, vo.getYear())
                .eq(EduClassStudentKey::getAreaCode, vo.getAreaCode())
                .eq(StringUtils.isNotBlank(vo.getSchoolId()), EduClassStudentKey::getSchoolId, vo.getSchoolId())
                .eq(!ObjectUtils.isEmpty(vo.getAdviserId()),EduClassStudentKey::getAdviserId,vo.getAdviserId())
                .eq(!ObjectUtils.isEmpty(vo.getStudentId()),EduClassStudentKey::getStudentId,vo.getStudentId())
        ;
        List<EduClassStudentKey> classStudentKeyList = eduClassStudentKeyService.list(queryWrapper);
        if (CollectionUtils.isEmpty(classStudentKeyList)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        List<EduClassStudentKeyInfoVO> resultList = null;

        //设置数据进行转换
        resultList = classStudentKeyList.stream().map(item -> {
            EduClassStudentKeyInfoVO infoVO = new EduClassStudentKeyInfoVO();
            BeanUtils.copyProperties(item, infoVO);

            //查询班主任信息进行设置
            EduClassAdviser classAdviser = eduClassAdviserService.getById(item.getAdviserId());
            if (classAdviser != null) {
                infoVO.setClassAdviserName(classAdviser.getFullName());
                infoVO.setClassAdviserTelphone(classAdviser.getTelphone());
            }
            //设置学校信息
            EduSchool eduSchool = eduSchoolService.getById(item.getSchoolId());
            if (eduSchool != null) {
                infoVO.setSchoolName(eduSchool.getShortName());
                infoVO.setSchoolNature(eduSchool.getSchoolNature());
                infoVO.setSchoolCategory(eduSchool.getSchoolCategory());
            }
            //设置学生信息
            EduClassStudent student = eduClassStudentService.getById(item.getStudentId());
            if (student != null) {
                infoVO.setFullName(student.getFullName());
                infoVO.setIdcard(student.getIdcard());
                infoVO.setCardType(student.getCardType());
                infoVO.setBirthYmd(student.getBirthYmd());
                infoVO.setSex(student.getSex());
                infoVO.setAge(student.getAge());
                infoVO.setFollowingFlag(student.getFollowingFlag());
                infoVO.setAddress(student.getAddress());
                infoVO.setHouseholdAddress(student.getHouseholdAddress());
                infoVO.setHouseAddress(student.getHouseAddress());
                infoVO.setScore(student.getScore());
                infoVO.setScoreChinese(student.getScoreChinese());
                infoVO.setScoreEnglish(student.getScoreEnglish());
                infoVO.setScoreMathematics(student.getScoreMathematics());
                infoVO.setSpecialityFlag(student.getSpecialityFlag());
                infoVO.setFatherName(student.getFatherName());
                infoVO.setFatherCardType(student.getFatherCardType());
                infoVO.setFatherIdcard(student.getFatherIdcard());
                infoVO.setFatherCellphone(student.getFatherCellphone());
                infoVO.setMotherName(student.getMotherName());
                infoVO.setMotherCardType(student.getMotherCardType());
                infoVO.setMotherIdcard(student.getMotherIdcard());
                infoVO.setMotherCellphone(student.getMotherCellphone());
                infoVO.setSerialNumber(student.getSerialNumber());
            }
            return infoVO;
        }).collect(Collectors.toList());
        // 不为空则获取分页结果
        PageInfo<EduClassStudentKeyInfoVO> pageInfo = new PageInfo<>(resultList);
        // 转义数据字典值
        dictHelper.valueToName(resultList, Arrays.asList(EduAreaCodeEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduClassStudentKey0002", title = "分班学生重点名单管理根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduClassStudentKeyInfoVO getById(EduClassStudentKeyKeyVO vo) {
        EduClassStudentKey entity = eduClassStudentKeyService.getById(vo.getStudentKeyId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduClassStudentKeyInfoVO classStudentKeyInfoVO = new EduClassStudentKeyInfoVO();
        BeanUtils.copyProperties(entity, classStudentKeyInfoVO);

        //查询班主任信息进行设置
        EduClassAdviser classAdviser = eduClassAdviserService.getById(entity.getAdviserId());
        if (classAdviser != null) {
            classStudentKeyInfoVO.setClassAdviserName(classAdviser.getFullName());
            classStudentKeyInfoVO.setClassAdviserTelphone(classAdviser.getTelphone());
        }
        //设置学校信息
        EduSchool eduSchool = eduSchoolService.getById(entity.getSchoolId());
        if (eduSchool != null) {
            classStudentKeyInfoVO.setSchoolName(eduSchool.getShortName());
            classStudentKeyInfoVO.setSchoolNature(eduSchool.getSchoolNature());
            classStudentKeyInfoVO.setSchoolCategory(eduSchool.getSchoolCategory());
        }
        //设置学生信息
        EduClassStudent student = eduClassStudentService.getById(entity.getStudentId());
        if (student != null) {
            classStudentKeyInfoVO.setFullName(student.getFullName());
            classStudentKeyInfoVO.setIdcard(student.getIdcard());
            classStudentKeyInfoVO.setCardType(student.getCardType());
            classStudentKeyInfoVO.setBirthYmd(student.getBirthYmd());
            classStudentKeyInfoVO.setSex(student.getSex());
            classStudentKeyInfoVO.setAge(student.getAge());
            classStudentKeyInfoVO.setFollowingFlag(student.getFollowingFlag());
            classStudentKeyInfoVO.setAddress(student.getAddress());
            classStudentKeyInfoVO.setHouseholdAddress(student.getHouseholdAddress());
            classStudentKeyInfoVO.setHouseAddress(student.getHouseAddress());
            classStudentKeyInfoVO.setScore(student.getScore());
            classStudentKeyInfoVO.setScoreChinese(student.getScoreChinese());
            classStudentKeyInfoVO.setScoreEnglish(student.getScoreEnglish());
            classStudentKeyInfoVO.setScoreMathematics(student.getScoreMathematics());
            classStudentKeyInfoVO.setSpecialityFlag(student.getSpecialityFlag());
            classStudentKeyInfoVO.setFatherName(student.getFatherName());
            classStudentKeyInfoVO.setFatherCardType(student.getFatherCardType());
            classStudentKeyInfoVO.setFatherIdcard(student.getFatherIdcard());
            classStudentKeyInfoVO.setFatherCellphone(student.getFatherCellphone());
            classStudentKeyInfoVO.setMotherName(student.getMotherName());
            classStudentKeyInfoVO.setMotherCardType(student.getMotherCardType());
            classStudentKeyInfoVO.setMotherIdcard(student.getMotherIdcard());
            classStudentKeyInfoVO.setMotherCellphone(student.getMotherCellphone());
            classStudentKeyInfoVO.setSerialNumber(student.getSerialNumber());
        }
        return classStudentKeyInfoVO;
    }

    /**
     * 保存前统一校验
     */
    @Override
    @OpApi(funcCode = "eduClassStudentKey0003", title = "分班学生重点名单管理保存前校验", funcType = FuncTypeEnum.other, checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduClassStudentKeyVO vo) {
        //基本校验
        if (ObjectUtils.isEmpty(vo.getYear())) {
            vo.setYear(eduHelper.thisYear());
        }
        if (ObjectUtils.isEmpty(vo.getAreaCode())) {
            vo.setAreaCode(SessionUtil.getAreaCode());
        }
        if (ObjectUtils.isEmpty(vo.getSchoolId())) {
            throw new AppException("所属学校不能为空！");
        }
        if (ObjectUtils.isEmpty(vo.getAdviserId())) {
            throw new AppException("班主任不能为空");
        }
        if (ObjectUtils.isEmpty(vo.getStudentId())) {
            throw new AppException("学生不能为空！");
        }
        //校验信息是否存在
        if (eduSchoolService.count(Wrappers.<EduSchool>lambdaQuery().eq(EduSchool::getOrgId,vo.getSchoolId())) == 0){
            throw new AppException("所选学校数据有误，刷新后重新选择！");
        }
        if (eduClassStudentService.count(Wrappers.<EduClassStudent>lambdaQuery()
                .eq(EduClassStudent::getStudentId,vo.getStudentId())) == 0){
            throw new AppException("所选学生数据有误，刷新后重新选择！");
        }
        if (eduClassAdviserService.count(Wrappers.<EduClassAdviser>lambdaQuery()
                .eq(EduClassAdviser::getAdviserId,vo.getAdviserId())) == 0){
            throw new AppException("所选班主任数据有误，刷新后重新选择！");
        }
    }

    @Override
    @OpApi(funcCode = "eduClassStudentKey0004", title = "分班学生重点名单管理新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduClassStudentKey0004",
            operationName = "分班学生重点名单管理新增",
            dataType = "studentKeyId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduClassStudentKeyVO add(EduClassStudentKeyVO vo) {
        //保存前校验
        checkSave(vo);
        //判断学生是否存在本年度重点班数据
        QueryWrapper<EduClassStudentKey> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                        .eq(EduClassStudentKey::getYear,eduHelper.thisYear())
                                .eq(EduClassStudentKey::getAreaCode,SessionUtil.getAreaCode())
                                        .eq(EduClassStudentKey::getStudentId,vo.getStudentId());
        long count = eduClassStudentKeyService.count(queryWrapper);
        if (count > 0){
            throw new AppException("该学生已录入重点学生名单了，无需重复录入");
        }
        //保存数据
        EduClassStudentKey entity = Convert.convert(EduClassStudentKey.class, vo);
        eduClassStudentKeyService.save(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setStudentKeyId(entity.getStudentKeyId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduClassStudentKey0005", title = "分班学生重点名单管理修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduClassStudentKey0005",
            operationName = "分班学生重点名单管理修改",
            dataType = "studentKeyId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduClassStudentKeyVO edit(EduClassStudentKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getStudentKeyId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduClassStudentKey oldEntity = eduClassStudentKeyService.getById(vo.getStudentKeyId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduClassStudentKey entity = Convert.convert(EduClassStudentKey.class, vo);
        eduClassStudentKeyService.updateById(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduClassStudentKey0006", title = "分班学生重点名单管理根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduClassStudentKey0006",
            operationName = "分班学生重点名单管理删除",
            dataType = "studentKeyId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduClassStudentKeyKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getStudentKeyId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduClassStudentKey entity = eduClassStudentKeyService.getById(vo.getStudentKeyId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduClassStudentKeyService.removeById(vo.getStudentKeyId());
    }

    @OpApi(funcCode = "eduClassStudentKey0007", title = "根据主键查询详情信息", funcType = FuncTypeEnum.query)
    @Override
    public EduClassStudentKeyVO queryByStudentKeyId(EduClassStudentKeyKeyVO vo) {
        EduClassStudentKey entity = eduClassStudentKeyService.getById(vo.getStudentKeyId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduClassStudentKeyVO eduClassStudentKeyVO = Convert.convert(EduClassStudentKeyVO.class, entity);
        return eduClassStudentKeyVO;
    }
}
